import pygame
import time
import serial
import math
#from pygame import joystick, event

pygame.init()
#joystick.init()
j = pygame.joystick.Joystick(0)
j.init()
ser = serial.Serial('COM3', 115200)
print 'Initialized Joystick : %s' % j.get_name()
last_throttle_position = 0.00;
try:
    while True:
        pygame.event.pump()
        #for i in range(0, j.get_numaxes()):
           # if j.get_axis(i) != 0.00:
            #    print 'Axis %i reads %.2f' % (i, j.get_axis(i))
        #for i in range(0, j.get_numbuttons()):
          #  if j.get_button(i) != 0:
           #     print 'Button %i reads %i' % (i, j.get_button(i))
        throttle_position = j.get_axis(2)
        if throttle_position != last_throttle_position:
            to_write = (-115 * throttle_position) + 140
            to_write = math.ceil(float(to_write))
            to_write = '%ss' % to_write
            print to_write
            ser.write(to_write)
            last_throttle_position = throttle_position
            time.sleep(1)
except KeyboardInterrupt:
    j.quit()